package com.yj.springbootzookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

public class Ticket implements Runnable {

    //票数
    private int ticket = 10;
    InterProcessLock lock;

    //使用curators 分布式锁
    public Ticket() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(2000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("192.168.152.101:2181").sessionTimeoutMs(60 * 1000).connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy).build();
        client.start();
        lock = new InterProcessMutex(client, "/lock");
    }

    @Override
    public void run() {
        while (true) {
            try {
                lock.acquire(3, TimeUnit.SECONDS);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName()+":" + ticket);
                    ticket--;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
}


class LockTest {


    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread win1 = new Thread(ticket, "窗口1");
        Thread win2 = new Thread(ticket, "窗口2");
        win1.start();
        win2.start();
    }
}